package com.ruoyi.order.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.merchant.api.RemoteMerchantService;
import com.ruoyi.merchant.api.domain.Merchant;
import com.ruoyi.order.common.UserContextHolder;
import com.ruoyi.order.enums.LogicDeleteEnum;
import com.ruoyi.order.enums.StatusEnum;
import com.ruoyi.order.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.EvaluationMapper;
import com.ruoyi.order.domain.Evaluation;
import com.ruoyi.order.service.IEvaluationService;

/**
 * 评价Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-12
 */
@Service
public class EvaluationServiceImpl implements IEvaluationService {
    @Autowired
    private EvaluationMapper evaluationMapper;

    @Autowired
    private RemoteMerchantService remoteMerchantService;

    /**
     * 查询评价
     *
     * @param eId 评价主键
     * @return 评价
     */
    @Override
    public Evaluation selectEvaluationByEId(Long eId) {
        return evaluationMapper.selectEvaluationByEId(eId);
    }

    /**
     * 查询评价列表
     *
     * @param evaluation 评价
     * @return 评价
     */
    @Override
    public List<Evaluation> selectEvaluationList(Evaluation evaluation) {
        return evaluationMapper.selectEvaluationList(evaluation);
    }

    /**
     * 新增评价
     *
     * @param evaluation 评价
     * @return 结果
     */
    @Override
    public int insertEvaluation(Evaluation evaluation) {
        //1、异常判断
        if (evaluation == null) {
            throw new RuntimeException("评价不能为空");
        }
        if (evaluation.getMerchantId() == null || evaluation.getSmId() == null || evaluation.getUserId() == null || evaluation.getOrderId() == null) {
            throw new RuntimeException("评价信息不存在，不能进行评价~");
        }
        //2、根据商家id获取商户名
        AjaxResult ajaxResult = remoteMerchantService.getInfo(evaluation.getMerchantId());
        // 将AjaxResult转为JSON字符串
        String jsonStr = JSONUtil.toJsonStr(ajaxResult);
        // 从JSON中提取data部分并转换为Merchant对象
        Merchant merchant = JSONUtil.toBean(JSONUtil.parseObj(jsonStr).getStr("data"), Merchant.class);
        Evaluation eva = Evaluation.builder().rating(evaluation
                .getRating())
                .content(evaluation.getContent())
                .images(evaluation.getImages())
                .evalTime(new Date())
                .name(evaluation.getName())
                .userName(evaluation.getUserName())
                .status(StatusEnum.SUCCESS.getStatus())
                .isDeleted(LogicDeleteEnum.NOT_DELETED.getStatus())
                .merchantId(evaluation.getMerchantId())
                .smId(evaluation.getSmId())
                .userId(evaluation.getUserId())
                .orderId(evaluation.getOrderId())
                .shopName(merchant.getShopName())
                .build();
        return evaluationMapper.insertEvaluation(eva);
    }

    /**
     * 修改评价
     * 管理端修改评价状态和逻辑删除
     *
     * @param evaluation 评价
     * @return 结果
     */
    @Override
    public int updateEvaluation(Evaluation evaluation) {
        if (evaluation == null) {
            throw new RuntimeException("评价不能为空");
        }
        //TODO  获取当前用户iD
        Long userId = 1L;
        if (!evaluation.getUserId().equals(userId)) {
            throw new RuntimeException("当前用户没有权限修改此评价");
        }
        return evaluationMapper.updateEvaluation(evaluation);
    }

    /**
     * 批量删除评价
     *
     * @param eIds 需要删除的评价主键
     * @return 结果
     */
    @Override
    public int deleteEvaluationByEIds(Long[] eIds) {
        for (Long eId : eIds) {
            Evaluation evaluation = Optional.ofNullable(eId).map(id -> evaluationMapper.selectEvaluationByEId(id)).orElseThrow(() -> new RuntimeException("评价ID不能为空"));
            if (evaluation == null) {
                throw new RuntimeException("当前评价有误，请检查");
            }
        }
        return evaluationMapper.deleteEvaluationByEIds(eIds);
    }

    /**
     * 删除评价信息
     *
     * @param eId 评价主键
     * @return 结果
     */
    @Override
    public int deleteEvaluationByEId(Long eId) {
        return evaluationMapper.deleteEvaluationByEId(eId);
    }


    /**
     * 平均分
     * @param
     * @return
     */
    public List<Evaluation> avgStatistics() {
       return evaluationMapper.selectAvgStatistics();

    }
}
